<?php
/**
 * Api to Handle Contact Creation
 * and document upload
 *
 */
use Hive\Mission;
use Hive\Mission\Announce;
use Fox\Core\Errors;
use Hive\Ressource;

$xview = Xview::instance();

if(isset($_POST))
{

	// First Name
	$fields['first_name'] =  $xview->val('fname');
	// Last Name
	$fields['last_name'] = $xview->val('lname');
	// Email
	$fields['email'] = $xview->val('email1');
	// Web Site Source
	$fields['source'] = $xview->val('source',Ressource::SOURCE_CORPORATE_WEBSITE);
	// Decode UTF8
	$fields = Fox\Utilities::UTF8Decode($fields);
	// Check if the request is associate to a job offer
	$aid = $xview->val('aid');
	$mid = $xview->val('mid');

	try {
		$contact = new Ressource();
		$fields['status'] = Ressource::STATUS_NEW;
		$fields['grouping'] = 1;
		$fields['creation_type'] = Ressource::CREATION_TYPE_WEBSITE;
		
		$contact->setFields($fields);
		$contact->create();
		$contact->uploadDocument(false);
		if(!empty($aid) && !empty($mid)) {
			try {
				Mission::className();
				$announce = Fox\Dao::load(Announce::className(),$aid.':'.$mid);
				$mission = $announce->mission();
				$missionid = $mission->getId();
				// Attach the Contact to the job offer with the status 
				$partner = new Mission\Partner();
				$partner->setFields(array('missionid' => $missionid,
							'partnerid' => $contact->getId(),
							'role' => Mission\Partner::ROLE_CANDIDATE,
							'status' => Mission\Partner::STATUS_DEFAULT,
							'announceid' => $aid));
				$partner->create();
				
				
			} catch(Fox\Object\Exception\NotExist $e) {
				// Can be possible but do nothing 
				// just add the contact 
			} catch(Fox\Object\Exception\Save $e) {
				// Should not happen
			}
		}
		
		$response = 'SUCCESS';
		// Send an Email To the Admin
		$mailer = new \Fox\Mail();
		// Sent Link Activation to the user
		$mailer->subject = Msg(Hive::BUNDLE,Hive::MAIL_RESUME_UPLOADED_TITLE);
		if(!isset($partner)) {
			$mailer->body = Msg(Hive::BUNDLE,
							Hive::MAIL_RESUME_UPLOADED_BODY,
							$fields['first_name'],
							$fields['last_name'],
							$fields['email'],
							$fields['source']);
		} else {
			$jobOfferRef = $announce->title.' [ '. $announce->reference.' ]';
			$mailer->body = Msg(Hive::BUNDLE,
							Hive::MAIL_RESUME_UPLOADED_JOBOFFER_BODY,
							$fields['first_name'].' '.$fields['last_name'].' '.$fields['email'],
							$fields['source'],
							$jobOfferRef);
		}
		$mailer->mailto = 'nkarsenty@orinea.com';
		$mailer->tryCreate();
		$mailer->send();
	}
	catch (Fox\Object\Exception\Save $e)
	{
		$response = Errors::pushMessage($e);
	}
	echo $response;
}